package com.szgr.baoyin.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.MyTool;
import com.szgr.baoyin.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * 注册
 */
public class RegisterActivity extends BaseActivity {

    private static final int REGISTER_BACK = 100;
    private TextView tv_getCode;
    private int minute = 60;
    private boolean isClick;
    private EditText et_phone;
    private EditText et_password;
    private EditText et_rePassword;
    private EditText et_code;
    private Intent regIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_register2);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initActionBar() {
        regIntent = getIntent();
        if(regIntent != null && regIntent.hasExtra("from")){
            actionBarTitle.setText("找回密码");
        }else {
            actionBarTitle.setText("注册");
        }
    }

    @Override
    public void initView() {
        tv_getCode = (TextView) findViewById(R.id.login_get_code);
        tv_getCode.setOnClickListener(this);

        et_phone = (EditText) findViewById(R.id.register_phone);
//        String phoneNumber = MyTool.getPhoneNumber(this);
//        et_phone.setText(phoneNumber.substring(3,14));
        et_password = (EditText) findViewById(R.id.register_password);
        et_rePassword = (EditText) findViewById(R.id.register_re_password);
        et_code = (EditText) findViewById(R.id.register_code);

        Button btn_reg = (Button) findViewById(R.id.register_btn);
        btn_reg.setOnClickListener(this);

        if(regIntent != null && regIntent.hasExtra("from")){
            btn_reg.setText("找回");
        }
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    tv_getCode.setText(String.valueOf(msg.obj) + "s");
                    break;
                case 1:
                    tv_getCode.setEnabled(true);
                    tv_getCode.setText("获取验证码");
                    break;
                case Constant.REQUEST_SUCCESS:
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putString("username",et_phone.getText().toString().trim());
                    bundle.putString("password",et_password.getText().toString().trim());
                    intent.putExtra("bundle",bundle);
                    setResult(REGISTER_BACK, intent);
                    finish();
                    break;
            }

        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.action_bar_left:
                finish();
                break;
            case R.id.login_get_code:
                if(!MyTool.isEmpty(et_phone)) {
                    isClick = true;
                    tv_getCode.setEnabled(false);
                    tv_getCode.setText("60s");

                    new Thread() {
                        @Override
                        public void run() {
                            while (isClick) {
                                try {
                                    sleep(1000);
                                    minute--;
                                    if (minute == 0) {
                                        minute = 60;
                                        isClick = false;
                                        mHandler.obtainMessage(1).sendToTarget();
                                        return;
                                    }
                                    mHandler.obtainMessage(0, minute).sendToTarget();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }.start();

                    getPhoneCode();
                }else{
                    ToastUtils.showToast("电话号码不能为空");
                }
                break;
            case R.id.register_btn:
                if(MyTool.isEmpty(et_phone)){
                    ToastUtils.showToast("手机号不能为空");
                    return;
                }
                if(MyTool.isEmpty(et_password)){
                    ToastUtils.showToast("密码不能为空");
                    return;
                }
                if(MyTool.isEmpty(et_rePassword)){
                    ToastUtils.showToast("确认密码不能为空");
                    return;
                }
                if(MyTool.isEmpty(et_code)){
                    ToastUtils.showToast("验证码不能为空");
                    return;
                }
                String password = et_password.getText().toString().trim();
                String rePassword = et_rePassword.getText().toString().trim();
                if(!password.equals(rePassword)){
                    ToastUtils.showToast("前后两次密码不一致");
                    return;
                }
                if(regIntent != null && regIntent.hasExtra("from")){
                    goFind();
                }else {
                    goRegister();
                }
                break;
        }
    }

    /**
     * 找回密码
     */
    private void goFind() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_FIND_PASSWORD,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("---find pass--->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String datas = jsonObject.getString("datas");
                            if(jsonObject.has("error") || jsonObject.has("errorcode")){
                                ToastUtils.showToast(jsonObject.getString("error"));
                            }else {
                                mHandler.obtainMessage(Constant.REQUEST_SUCCESS).sendToTarget();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("username",et_phone.getText().toString().trim());
                map.put("password",et_password.getText().toString().trim());
                map.put("password_confirm",et_rePassword.getText().toString().trim());
                map.put("client","android");
                map.put("code",et_code.getText().toString().trim());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    /**
     * 注册
     */
    private void goRegister() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_REGISTER,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String code = jsonObject.getString("code");
                            JSONObject datas = jsonObject.getJSONObject("datas");
                            if(datas.has("error") || datas.has("errorcode")){
                                ToastUtils.showToast(datas.getString("error"));
                            }else {
                                mHandler.obtainMessage(Constant.REQUEST_SUCCESS).sendToTarget();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtils.showToast("注册失败，请检查网络后重试。");
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("username",et_phone.getText().toString().trim());
                map.put("password",et_password.getText().toString().trim());
                map.put("password_confirm",et_rePassword.getText().toString().trim());
                map.put("client","android");
                map.put("code",et_code.getText().toString().trim());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    /**
     * 网络获取验证码
     */
    private void getPhoneCode() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_GET_CODE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String code = jsonObject.getString("code");
                            if("200".equals(code)){
                                JSONObject datas = jsonObject.getJSONObject("datas");
                                ToastUtils.showToast(datas.getString("msg"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtils.showToast("获取验证码失败");
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("username",et_phone.getText().toString().trim());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }
}
